package cz.acies.data.process;

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public abstract class AbstractProcessor
{
	private ServletContext application;
	private HttpSession session;
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	protected Map<String, Object> params = new HashMap<String, Object>();
	
	// -----  -----------------------------------------------------------------
	
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		this.setRequest(request);
		this.setResponse(response);
		
		params = makeParams(request);
		try {			
			PrintWriter out = response.getWriter();
			String  result = execute(params);
			out.print(result);
		} catch (Exception exc) {
			exc.printStackTrace();
		}
	}
	
	public abstract String execute(Map<String, Object> params); 
	
	protected Map<String, Object> makeParams(HttpServletRequest request) {
		try {
			Enumeration<String> e = request.getParameterNames();
			while (e.hasMoreElements()) {
				String key =  e.nextElement();
				params.put(key, request.getParameter(key));
			}
			Enumeration<String> ea = request.getAttributeNames();
			while (ea.hasMoreElements()) {
				String key =  ea.nextElement();
				params.put(key, request.getParameter(key));
			}
			//params.putAll(headerToMap(data));
		} catch (Exception exc) {
			exc.printStackTrace();
		}
		return params;
	}
	
	protected Map<String, Object> headerToMap(String data) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<String> list = Arrays.asList(data.split("&"));
		for (String s : list) {
			String as[] = s.split("=");
			if (as.length == 2) {
				result.put(as[0], as[1]);
			} else if (as.length == 1) {
				result.put(as[0], "");
			}
		}
		return result;
	}

	// -----  -----------------------------------------------------------------
	
	public ServletContext application() {
		return application;
	}
	
	public void setServletContext(ServletContext application) {
		this.application = application;
	}
	
	public HttpSession getSession() {
		return session;
	}
	
	public void setSession(HttpSession session) {
		this.session = session;
	}
	
	public HttpServletRequest request() {
		return request;
	}
	
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	public HttpServletResponse response() {
		return response;
	}
	
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
}
